package com.hyperz;

import java.util.HashMap;

import com.hyperz.utils.Repository;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.app.ListFragment;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;

public class RepoTreeViewer extends Activity {
	
	@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        setContentView(R.layout.repo_browser_list);
    }
	
	/**
     * This is a secondary activity, to show what the user has selected
     * when the screen is not large enough to show it all in one activity.
     */
    public static class DetailsActivity extends Activity {
    	
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            if (getResources().getConfiguration().orientation
                    == Configuration.ORIENTATION_LANDSCAPE) {
                // If the screen is now in landscape mode, we can show the
                // dialog in-line with the list so we don't need this activity.
                finish();
                return;
            }
            
            if (savedInstanceState == null) {
                // During initial setup, plug in the details fragment.
                ItemDetailsFragment details = new ItemDetailsFragment();
                details.setArguments(getIntent().getExtras());
                getFragmentManager().beginTransaction().add(android.R.id.content, details).commit();
            }
        }
    }
	
	public static class ListViewFragment extends ListFragment {
		private boolean mDualPane;
		private int mCurCheckPosition = 0;
		private Bundle detailsBundle = null;
		
		/***
		 * Called first once this fragment is associated with the activity
		 */
		@Override
		public void onAttach(Activity a) {
			super.onAttach(a);
			if (detailsBundle == null)
				detailsBundle = a.getIntent().getExtras();
		}
		
		/***
		 * called second, does the initial creation of the fragment
		 */
		@Override
		public void onCreate(Bundle savedInstanceState) {
			super.onCreate(savedInstanceState);
			if (savedInstanceState != null)
				detailsBundle = savedInstanceState;
		}
		
		/***
		 * called fourth [after onCreateView(li, vg, b)] tells the fragment that the 
		 * parent activity has completed it's own onCreate
		 */
		@Override
		public void onActivityCreated(Bundle savedInstanceState) {
			super.onActivityCreated(savedInstanceState);
			//set list adapter
			getListView().setAdapter(new FileListAdapter(this.getActivity(), detailsBundle));
			
			View detailsFrame = getActivity().findViewById(R.id.details);
			mDualPane = detailsFrame != null && detailsFrame.getVisibility() == View.VISIBLE;
			
			if (savedInstanceState != null) {
                // Restore last state for checked position.
                mCurCheckPosition = savedInstanceState.getInt("curChoice", 0);
            }
			
			if (mDualPane) {
                // In dual-pane mode, the list view highlights the selected item.
                getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
                // Make sure our UI is in the correct state.
                showDetails(mCurCheckPosition);
            }
		}
		
		@Override
		public void onListItemClick(ListView l, View v, int position, long id) {
			super.onListItemClick(l, v, position, id);
		}
		
		@Override
		public void onSaveInstanceState(Bundle outState) {
			outState = detailsBundle;
			
			super.onSaveInstanceState(outState);
			outState.putInt("curChoice", mCurCheckPosition);
		}
		
		/**
         * Helper function to show the details of a selected item, either by
         * displaying a fragment in-place in the current UI, or starting a
         * whole new activity in which it is displayed.
         */
		void showDetails(int index) {
            mCurCheckPosition = index;
            
			if (mDualPane) {
                // We can display everything in-place with fragments, so update
                // the list to highlight the selected item and show the data.
                getListView().setItemChecked(index, true);

                // Check what fragment is currently shown, replace if needed.
                ItemDetailsFragment details = (ItemDetailsFragment)
                        getFragmentManager().findFragmentById(R.id.details);
                if (details == null || details.getShownIndex() != index) {
                    // Make new fragment to show this selection.
                    details = ItemDetailsFragment.newInstance(index);

                    // Execute a transaction, replacing any existing fragment
                    // with this one inside the frame.
                    FragmentTransaction ft = getFragmentManager().beginTransaction();
                    ft.replace(R.id.details, details);
                    ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
                    ft.commit();
                }

            } else {
                // Otherwise we need to launch a new activity to display
                // the dialog fragment with selected text.
                Intent intent = new Intent();
                intent.setClass(getActivity(), DetailsActivity.class);
                intent.putExtra("index", index);
                startActivity(intent);
            }
		}
	}
	
    
    /**
     * This is the secondary fragment, displaying the details of a particular
     * item.
     */
    public static class ItemDetailsFragment extends Fragment {
    	/**
         * Create a new instance of DetailsFragment, initialized to
         * show the text at 'index'.
         */
        public static ItemDetailsFragment newInstance(int index) {
        	ItemDetailsFragment f = new ItemDetailsFragment();
        	
            // Supply index input as an argument.
            Bundle args = new Bundle();
            args.putInt("index", index);
            f.setArguments(args);

            return f;
        }

        public int getShownIndex() {
            return getArguments().getInt("index", 0);
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            if (container == null) {
                // We have different layouts, and in one of them this
                // fragment's containing frame doesn't exist.  The fragment
                // may still be created from its saved state, but there is
                // no reason to try to create its view hierarchy because it
                // won't be displayed.  Note this is not needed -- we could
                // just run the code below, where we would create and return
                // the view hierarchy; it would just never be used.
                return null;
            }
            
            ScrollView scroller = new ScrollView(getActivity());
            TextView text = new TextView(getActivity());
            int padding = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
                    4, getActivity().getResources().getDisplayMetrics());
            text.setPadding(padding, padding, padding, padding);
            scroller.addView(text);
            //text.setText();
            return scroller;
        }
    }
    
    public static class FileListAdapter extends BaseAdapter {
    	private LayoutInflater inflater;
    	private HashMap<Integer, String> fileList = null;
    	
    	public FileListAdapter(Context context, Bundle bundle) {
            super();
            
            inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            
            Repository repo = new Repository(context, bundle);
            fileList = repo.getFileList();
    	}
    	
		@Override
		public int getCount() {
			return fileList.size();
		}

		@Override
		public String getItem(int position) {
			return fileList.get(position);
		}
		
		@Override
		public long getItemId(int position) {
			return 0;
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View v;
			
			if (convertView == null) {
                v = inflater.inflate(R.layout.repo_browser_list_item, null);
	        } else {
	            v = convertView;
	        }
			
			((TextView) v.findViewById(R.id.item_name)).setText(getItem(position));
			((TextView) v.findViewById(R.id.item_revision)).setText("99");
			return v;
		}
    	
    }
}
